package com.leanit.pmc.verify;

import com.leanit.pmc.common.util.VerifyBean;
import com.leanit.pmc.common.util.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 验证码controller
 * Created by zhangmeng on 2016/3/21.
 */
@Controller
@RequestMapping("/verify")
public class VerifyController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/generateCode", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.HEAD})
    public void generateCode(HttpSession session, HttpServletResponse response) {
        VerifyBean verify = VerifyCodeUtils.generateVerify();
        if (null != verify) {
            session.setAttribute("VERIFY_CODE_PMC", verify.getVerifyCode());
        }
        response.setContentType("image/gif");
        try {
            ImageIO.write(verify.getImgBuffer(), "jpg", response.getOutputStream());
        } catch (Exception e) {
            logger.error("生成验证码错误", e);
        }
    }

    @RequestMapping(value = "/verifyCode", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.HEAD})
    @ResponseBody
    public boolean verifyCode(HttpSession session, String code) {
        return VerifyCodeUtils.verifyCodeIgnoreCase(session, code);
    }

}
